<?php
/**
 *作   者：zhen
 * 
 *创建时间：2016-02-27
 * 
 *类   名：公用操作   chat Class
 * 
 *@function 操作类
 *       
 ***/
use \GatewayWorker\Lib\Gateway;  

require_once dirname(__DIR__) . '/public.class.model.php';
class Server_Timer_Model extends Public_Model
{
	
	/***************************
			common function	
	***************************/
	
	/*
		
	*/
	public function updateTimerID($arrData)
	{
		//echo "updateTimerID";
		$operation = $arrData['operation'];
		$room_id = $arrData['room_id'];
		$data = $arrData['data'];

		$timer_id = $data['timer_id'];
		//保存timer_id
		$this->updateRoomTimerId($room_id, $timer_id);
		
		return true;
	}
	
	public function startGamePassive($arrData)
	{
		

		$operation = $arrData['operation'];
		$room_id = $arrData['room_id'];
		$data = $arrData['data'];

		$timer_id = $data['timer_id'];

		$this->writeLog("[$room_id] function(startGamePassive):默认开局");

		$current_timer_id = $this->queryRoomTimerId($room_id);
		if($current_timer_id == $timer_id){
			$this->updateRoomTimerId($room_id, -1);
			$this->updateReadyTime($room_id, -1);
		}
		else
		{
			$this->writeLog("function(startGamePassive):timer_id($current_timer_id) error:".$timer_id." in file".__FILE__." on Line ".__LINE__);
			return false;
		}

		$this->startGame($room_id, true);

		return true;
	}

	//抢庄时间结束自动进入下注模式
	public function grabPassive($arrData)
	{
		

		$operation = $arrData['operation'];
		$room_id = $arrData['room_id'];
		$data = $arrData['data'];

		$timer_id = $data['timer_id'];

		$this->writeLog("[$room_id] 抢庄时间结束");

		$current_timer_id = $this->queryRoomTimerId($room_id);
		if($current_timer_id == $timer_id){
			$this->updateRoomTimerId($room_id, -1);
			$this->updateReadyTime($room_id, -1);
		} else {
			$this->writeLog("function(grabPassive):timer_id($current_timer_id) error:".$timer_id." in file".__FILE__." on Line ".__LINE__);
			return false;
		}
		$this->grabPassiveOpt($room_id);
		
		return true;
	}

	public function shufflePassive($arrData)
	{
		

		$operation = $arrData['operation'];
		$room_id = $arrData['room_id'];
		$data = $arrData['data'];

		$timer_id = $data['timer_id'];

		$this->writeLog("[$room_id] 自动洗牌");

		$current_timer_id = $this->queryRoomTimerId($room_id);
		if($current_timer_id == $timer_id){
			$this->updateRoomTimerId($room_id, -1);
			$this->updateReadyTime($room_id, -1);
		} else {
			$this->writeLog("function(shufflePassive):timer_id($current_timer_id) error:".$timer_id." in file".__FILE__." on Line ".__LINE__);
			return false;
		}

		//天门自动洗牌
		$banker_id = $this->queryBanker($room_id);
		$Redis_Model = Redis_Model::getModelObject();
		$replyArr = array("[roomid]"=>$room_id);
		$RoomSequence_Key = strtr(Redis_Const::RoomSequence_Key, $replyArr);
		$banker_seat_number = $Redis_Model->getZscore($RoomSequence_Key, $banker_id);

		$tianmen_seat_number = $banker_seat_number < 3 ? ($banker_seat_number + 2) : ($banker_seat_number - 2);
		$tianmen_id = -1;
		$zrange_array['is_zrange'] = true;
		$zrange_array['key'] = $RoomSequence_Key;
		$zrange_array['start'] = 0;
		$zrange_array['stop'] = -1;
		$zrange_array['WITHSCORES'] = 1;
		$members = $Redis_Model->zrangeSet($zrange_array);
		if(is_array($members) ){
			foreach ($members as $account_id => $seat_number) {
				if($seat_number == $tianmen_seat_number){
					$tianmen_id = $account_id;
				}
			}
		}

		$msg_arr = array(
			'result' => 0,
			'operation' => 'ShufflingCard',
			'result_message' => "洗牌",
			'data' => array(
				'account_id' => $tianmen_id,
				)
			);
		$this->pushMessageToGroup($room_id, $msg_arr);
			
		$this->startBetRound($room_id);
		
		return true;
	}

	//下注时间结束自动进入摊牌模式
	public function betPassive($arrData)
	{
		

		$operation = $arrData['operation'];
		$room_id = $arrData['room_id'];
		$data = $arrData['data'];

		$timer_id = $data['timer_id'];

		$this->writeLog("[$room_id] 下注完毕");

		$current_timer_id = $this->queryRoomTimerId($room_id);
		if($current_timer_id == $timer_id){
			$this->updateRoomTimerId($room_id, -1);
			$this->updateReadyTime($room_id, -1);
		}
		else
		{
			$this->writeLog("function(betPassive):timer_id($current_timer_id) error:".$timer_id." in file".__FILE__." on Line ".__LINE__);
			return false;
		}

		$this->startDealRound($room_id);
		return true;
	}

	//自动洗牌
	public function dealPassive($arrData)
	{
		$operation = $arrData['operation'];
		$room_id = $arrData['room_id'];
		$data = $arrData['data'];

		$timer_id = $data['timer_id'];

		$this->writeLog("[$room_id] 自动洗牌");

		$current_timer_id = $this->queryRoomTimerId($room_id);
		if($current_timer_id == $timer_id){
			$this->updateRoomTimerId($room_id, -1);
			$this->updateReadyTime($room_id, -1);
		}
		else
		{
			$this->writeLog("function(betPassive):timer_id($current_timer_id) error:".$timer_id." in file".__FILE__." on Line ".__LINE__);
			return false;
		}

		$banker_id = $this->queryBanker($room_id);
		//通知用户修改状态
		$msg_arr = array(
			'result' => 0,
			'operation' => 'DealingCard',
			'result_message' => "发牌",
			'data' => array(
				'account_id' => $banker_id,
				'type' => 1,
				'dice_a' => mt_rand(1, 6),
				'dice_b' => mt_rand(1, 6)
				)
			);
		$this->pushMessageToGroup($room_id, $msg_arr);

		$this->startShowRound($room_id);

		return true;
	}

	//摊牌时间结束自动进入结算
	public function showPassive($arrData)
	{
		$operation = $arrData['operation'];
		$room_id = $arrData['room_id'];
		$data = $arrData['data'];

		$timer_id = $data['timer_id'];

		$this->writeLog("[$room_id] 摊牌完毕");

		$current_timer_id = $this->queryRoomTimerId($room_id);
		if($current_timer_id == $timer_id){
			$this->updateRoomTimerId($room_id, -1);
			$this->updateReadyTime($room_id, -1);
		}
		else
		{
			$this->writeLog("function(showPassive):timer_id($current_timer_id) error:".$timer_id." in file".__FILE__." on Line ".__LINE__);
			return false;
		}

		//进入结算环节
		$this->startWinRound($room_id);
		
		return true;
	}

	//摊牌时间结束自动进入结算
	public function nextHalfPassive($arrData)
	{
		$operation = $arrData['operation'];
		$room_id = $arrData['room_id'];
		$data = $arrData['data'];

		$timer_id = $data['timer_id'];

		$this->writeLog("[$room_id] 下半场开始了");

		$current_timer_id = $this->queryRoomTimerId($room_id);
		if($current_timer_id == $timer_id){
			$this->updateRoomTimerId($room_id, -1);
			$this->updateReadyTime($room_id, -1);
		}
		else
		{
			$this->writeLog("function(nextHalfPassive):timer_id($current_timer_id) error:".$timer_id." in file".__FILE__." on Line ".__LINE__);
			return false;
		}

		$this->startBetRound($room_id);
		
		return true;
	}


	//清理房间
	public function clearRoomPassive($arrData)
	{
		$operation = $arrData['operation'];
		$room_id = $arrData['room_id'];
		$data = $arrData['data'];

		$timer_id = $data['timer_id'];

		$this->writeLog("[$room_id ] 触发自动清房间");

		$current_timer_id = $this->queryRoomTimerId($room_id);
		if($current_timer_id == $timer_id){
			$this->updateRoomTimerId($room_id, -1);
			$this->updateReadyTime($room_id, -1);
		} else {
			//timer对不上，返回
			$this->writeLog("function(clearRoomPassive):timer_id($current_timer_id) error:".$timer_id." in file".__FILE__." on Line ".__LINE__);
			return false;
		}

		$clients_of_groupid = Gateway::getClientSessionsByGroup($room_id);
		//判断是否全部人离线
		if(count($clients_of_groupid) > 0)
		{
			$this->writeLog("[$room_id] 房有人不清理");
			return false;
		}

		$MMYSQL = $this->initMysql();
		$Redis_Model = Redis_Model::getModelObject();
		$replyArr = array("[roomid]"=>$room_id);

		$game_num = $this->queryGameNumber($room_id);
		$creator = $this->queryCreator($room_id);

        $creatorInfo = $MMYSQL->row("select * from ".WX_Account." where account_id=".$creator);
        if ($creatorInfo['is_manage_on'] == 1 && $game_num == 0){
            $this->writeLog("function(clearRoomPassive):房间($room_id)开启了俱乐部，并且没有玩过，不清理");
            return false;
        }
		if(Game::PaymentType_Creator == Config::Ticket_Mode && $game_num==0 && $creator>0)	//退换给房主
		{
			$spend_ticket_count = $this->queryTicketCount($room_id);
			$this->balanceTicket($room_id, $creator, - $spend_ticket_count);
		}

		//保存积分榜
		if($game_num > 0){
			$Room_Key = strtr(Redis_Const::Room_Key, $replyArr);
			$round = $Redis_Model->hincrbyField($Room_Key, Redis_Const::Room_Field_GameRound, 1);
			$this->writeLog("[$room_id] 第".($round-1)."轮 结束!");

			$setting = $this->queryRoomSetting($room_id);
			//$round = $setting['ground'];
			$game_info['room_id'] = $room_id;
			$game_info['game_type'] = Game::Game_Type;
			$game_info['dealer_num'] = Config::Dealer_Num;
			$game_info['round'] = $round-1;

			$scoreboard = array();
			if(isset($setting['scoreboard']) && $setting['scoreboard']){
				$board_json_str = $setting['scoreboard'];
				$scoreboard = json_decode($board_json_str, true); //转为关联数组
			} else {
				//积分榜为空
				$scoreboard = array();
				$board_json_str = "";
			}

			$ticket_checked_user = $this->queryTicketCheckedUser($room_id);
			foreach ($scoreboard as $key => $value) {
				if(!in_array($key, $ticket_checked_user)){
					//未扣房卡的用户不显示在积分榜上
					unset($scoreboard[$key]);
				}
			}
			$save_scoreboard = $scoreboard;

			$banker_id = $this->queryBanker($room_id);
			$banker_score = $this->queryBankerScore($room_id);

			foreach ($scoreboard as $account_id => $score) {
				$account_sql = 'select nickname from '.WX_Account.' where account_id ='.$account_id;
				$name = $MMYSQL->single($account_sql);
				if($banker_id == $account_id)
				{
					$score -= $banker_score;
					$save_scoreboard[$account_id] = $score;
				}
			}

			$board_json_str = json_encode($save_scoreboard);

			$name_board = array();
			foreach ($save_scoreboard as $account_id => $score) {
				$account_sql = 'select nickname from '.WX_Account.' where account_id ='.$account_id;
				$name = $MMYSQL->single($account_sql);
				$name_board[] = array('name'=>$name, 'score'=>$score, 'account_id'=>$account_id);
			}

			//规则文本
			$rule_text = $this->formatRuleText($room_id);
			$balance_scoreboard = array('time'=>time(), 'scoreboard'=>$name_board,'game_num'=>$game_num);
			$balance_board_json_str = json_encode($balance_scoreboard['scoreboard']);

			$start_time = isset($setting[Redis_Const::Room_Field_StartTime])?$setting[Redis_Const::Room_Field_StartTime]:1;
			
			$board_array['start_time'] = $start_time;
			$board_array['create_time'] = time();
			$board_array['is_delete'] = G_CONST::IS_FALSE;
			$board_array['game_type'] = Game::Game_Type;
			$board_array['room_id'] = $room_id;
			$board_array['round'] = $round - 1;
			$board_array['game_num'] = $game_num;
			$board_array['rule_text'] = $rule_text;
			$board_array['board'] = $board_json_str;
			$board_array['balance_board'] = $balance_board_json_str;
			$board_id = $MMYSQL->insertReturnID(Room_Scoreboard,$board_array);

			//保存用户积分
			$game_info['score_board'] = $save_scoreboard;
			$this->saveAccountGameScore($game_info);
		}

		//关闭房间
		$this->initRoomData($room_id);

		$this->writeLog("[$room_id] 房间清理完毕!");

		return true;
	}







}